<?php
class Users
{
    private $db;
    private $session;

    public $validationRules = array(
        'UserName' => "/^[A-Za-z0-9\.\-\'_]{3,50}$/",
        'UserEmail' => "/^[A-Za-z0-9\._%\-]+@[A-Za-z0-9\.\-]+\.[A-Za-z]{2,4}$/",
        'Password' => "/^.{3,50}$/"
    );

    public function __construct()
    {
        $this->db = getModule('Db');
        $this->session = getModule('Session');
    }

    /**
     * Input must be array
     * Array contents:
     * ['UserName']
     * ['UserEmail']
     * ['FirstName']
     * ['LastName']
     * ['Password']
     * ['PasswordRepeat']
     *
     * @param array $user
     * @return string
     */
    public function Register($user = array())
    {
        if(!preg_match($this->validationRules['UserName'], $user['UserName']))
        {
            return 'UserNameInvalid';
        }

        if(!preg_match($this->validationRules['UserEmail'], $user['UserEmail']))
        {
            return 'UserEmailInvalid';
        }

        if(!preg_match($this->validationRules['Password'], $user['Password']))
        {
            return 'PasswordInvalid';
        }

        if($this->UsernameExists($user['UserName']))
        {
            return 'UserNameExists';
        }

        if($this->EmailExists($user['UserEmail']))
        {
            return 'UserEmailExists';
        }

        if($user['Password'] != $user['PasswordRepeat'])
        {
            return 'PasswordsDontMatch';
        }

        $this->db->exec('INSERT INTO `users` (`UserName`, `UserEmail`, `Password`, `FirstName`, `LastName`)
                         VALUES(:UserName, :UserEmail, :Password, :FirstName, :LastName)',
        array('UserName' => $user['UserName'],
              'UserEmail' => $user['UserEmail'],
              'Password' => md5($user['Password']),
              'FirstName' => $user['FirstName'],
              'LastName' => $user['LastName']));

        return 'Added';
    }

    /**
     * Input must be array
     * Array contents:
     * ['UserName']
     * ['Password']
     *
     * @param array $user
     * @return int
     */
    public function CheckLogin($user = array())
    {
        return (int)$this->db->getSingle('SELECT `ID`
                                          FROM `users`
                                          WHERE (`UserName` = :username
                                          OR `UserEmail` = :username)
                                          AND `Password` = :password',
                                          array('username' => $user['UserName'], 'password' => md5($user['Password'])));
    }

    /**
     * Input must be array
     * Array contents:
     * ['UserName']
     * ['Password']
     *
     * @param array $user
     * @return int
     */
    public function CheckAdminLogin($user = array())
    {
        return (int)$this->db->getSingle('SELECT `ID`
                                          FROM `users`
                                          WHERE (`UserName` = :username
                                          OR `UserEmail` = :username)
                                          AND `Password` = :password
                                          AND `GroupID` = 1',
                                          array('username' => $user['UserName'], 'password' => md5($user['Password'])));
    }

    public function UsernameExists($username)
    {
        $res = (int)$this->db->getSingle('SELECT COUNT(`ID`)
                                          FROM `users`
                                          WHERE `UserName` = :username',
                                          array('username' => $username));
        return $res > 0;
    }

    public function EmailExists($email)
    {
        $res = (int)$this->db->getSingle('SELECT COUNT(`ID`)
                                          FROM `users`
                                          WHERE `UserEmail` = :email',
                                          array('email' => $email));
        return $res > 0;
    }

    /**
     * Input must be array
     * Array contents
     * ['ID']
     *
     * @param array $user
     * @return void
     */
    public function LoginUser($user = array())
    {
        $this->session->UserID = $user['ID'];
    }

    public function LoginAdmin($user = array())
    {
        $this->session->UserID = $user['ID'];
        $this->session->GroupID = 1;
    }

    public function IsUser()
    {
        return (bool)$this->session->UserID;
    }

    public function IsAdmin()
    {
        return (bool)$this->session->UserID && $this->session->GroupID == 1;
    }

    public function GetUserID()
    {
        return (int)$this->session->UserID;
    }

    public function GetUserData($ID = null)
    {
        if(!$ID)
        {
            $ID = $this->GetUserID();
        }

        return $this->db->getRow('SELECT *
                                  FROM `users`
                                  WHERE `ID` = :UserID',
                                  array('UserID' => (int)$ID));
    }

    public function LogoutUser()
    {
        $this->session->Destroy();
    }
}
?>